PG = require('fckoa/db/pg')
b64id = require 'fckoa/util/b64id'
passport = require('koa-passport')
{CACHE} = require('fckoa/db/redis')

passport.serializeUser((user_id, done) ->
    done(null, user_id)
)

passport.deserializeUser((user_id, done) ->
    return done(null, user_id)
)
# session = require('koa-session2')

MONTH = 86400*30
SESSION_KEY = "I"
SESSION = require '../_session'

session = (ctx, next)->
    I = ctx.header.i
    passport = {}
    if I and I.length==24
        user_id = await SESSION.user_id(I)
        if user_id
            passport.user = user_id
    ctx.session = {
        passport
    }
    await next()
    user = ctx.session.passport.user
    if user != user_id
        if user
            await SESSION.bind(user, I)
        else
            await SESSION.logout(user_id)


module.exports = [
    session
    passport.initialize()
    passport.session()
]
